import axios from 'axios';
import { Message } from 'element-ui';
import qs from 'qs';
import { API_HOST } from '@/utils/constants';

class HTTP {
  constructor() {
    this.instance = axios.create({
      baseURL: API_HOST,
      withCredentials: false,
    });
    this.instance.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('token');
        token && (config.headers['X-LeoYoo-Admin-Token'] = token);
        return config;
      },
      (error) => (Promise.reject(error)),
    );
    this.instance.interceptors.response.use(
      (response) => {
        const { data, code, msg } = response.data;
        if (code !== 200) {
          Message.error(msg);
          return Promise.reject(response.data);
        }
        return data;
      },
      (error) => {
        console.log('http error', error.response);
        if (error.response) {
          const { status } = error.response;
          if (status === 401) {
            Message.error('请重新登录！');
            localStorage.clear();
            window.location.href = '/login';
          } else {
            return Promise.reject(error);
          }
        }
        return Promise.reject(error);
      },
    );
  }

  install = (Vue) => {
    Vue.prototype.$http = this.instance;
  };

  get(url, params, options = {}) {
    return this.instance.get(url, {
      params: {
        data: params,
      },
      paramsSerializer: (query) => (qs.stringify(query, { arrayFormat: 'repeat' })),
      ...options,
    });
  }

  post(url, params, options) {
    return this.instance.post(url, {
      data: params,
    }, options);
  }

  put(url, params) {
    return this.instance.put(url, {
      data: params,
    });
  }

  delete(url, params) {
    return this.instance.delete(url, {
      params: { data: params },
      paramsSerializer: (query) => (qs.stringify(query, { arrayFormat: 'repeat' })),
    });
  }

  formPost(url, params) {
    return this.instance.post(url, qs.stringify(params));
  }
}

export default new HTTP();
